package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisCacheClient;
import com.hmdp.utils.RedisData;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static com.hmdp.utils.RedisConstants.*;
@Service
@RequiredArgsConstructor
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    private final StringRedisTemplate stringRedisTemplate;

    private final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Resource
    private final RedisCacheClient redisCacheClient;

    private boolean tryLock(String lockKey){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unLock(String lockKey){
        stringRedisTemplate.delete(lockKey);
    }

    @Override
    @Transactional
    public Result queryById(Long id) {
        //缓存穿透(使用工具封装)
        Shop shop = redisCacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class,this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //逻辑过期解决缓存击穿
        //Shop shop = queryByIdLockExpire(id);

        //互斥锁解决缓存击穿
        //Shop shop = queryByIdLock(id);

        if(shop==null){
            return Result.fail("当前商铺不存在");
        }
        return Result.ok(shop);
    }

    //1.使用缓存空值防止缓存穿透
    //2.使用互斥锁防止缓存击穿
    private Shop queryByIdLock(Long id){
        String key = CACHE_SHOP_KEY+id;
        String s = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(s)){
            Shop shop = JSONUtil.toBean(s,Shop.class);
            return shop;
        }
        if(s!=null){
            return null;
        }
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            boolean flag = tryLock(lockKey);
            if (!flag){
                Thread.sleep(50);
                return queryByIdLock(id);
            }
            Shop shop = getById(id);
            Thread.sleep(200);
            if(shop==null){
                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return shop;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            unLock(lockKey);
        }
    }

    //使用互斥锁+逻辑过期防止缓存击穿
    //该方法在缓存中获取不到数据则直接返回null,用于直接存入缓存中的热点数据
    private Shop queryByIdLockExpire(Long id){
        String key = CACHE_SHOP_KEY+id;
        String s = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(s)){
            return null;
        }
        RedisData redisData = JSONUtil.toBean(s,RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject jsonObject = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(jsonObject, Shop.class);
        if(expireTime.isAfter(LocalDateTime.now())){
            //未过期 直接返回
            return shop;
        }
        //过期 使用互斥锁重建缓存
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if(isLock){
            //再次查询过期时间,防止多次重建
            String s1 = stringRedisTemplate.opsForValue().get(key);
            RedisData redisDataCheck = JSONUtil.toBean(s1, RedisData.class);
            LocalDateTime expireTimeCheck = redisDataCheck.getExpireTime();
            if(expireTimeCheck.isAfter(LocalDateTime.now())){
                JSONObject jsonObjectCheck = (JSONObject) redisData.getData();
                shop = JSONUtil.toBean(jsonObjectCheck, Shop.class);
                return shop;
            }
            //检查后发现未重建,则重建缓存
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    this.addShopsToCache(id, CACHE_SHOP_TTL);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    unLock(lockKey);
                }
            });
        }
        //未获取到锁,返回已过期数据
        return shop;
    }

    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id==null){
            return Result.fail("当前商铺不存在");
        }
        updateById(shop);
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    //缓存逻辑过期店铺信息方法封装
    public void addShopsToCache(Long shopId,Long ttlSeconds) throws InterruptedException {
        RedisData redisData = new RedisData(LocalDateTime.now().plusSeconds(ttlSeconds),getById(shopId));
        Thread.sleep(200);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+shopId,JSONUtil.toJsonStr(redisData));
    }

}
